package com.dayatang.hrm.compensation.domain;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.context.support.MessageSourceAccessor;

import com.dayatang.commons.domain.AbstractEntity;
import com.dayatang.commons.domain.DataType;
import com.dayatang.commons.domain.InstanceFactory;
import com.dayatang.commons.domain.Value;
import com.dayatang.hrm.compensation.context.CompensationMessageSource;
import com.dayatang.hrm.compensation.policy.DataCalculatePolicy;
import com.dayatang.hrm.compensation.vo.FiscalPeriodRangeSetting;
import com.dayatang.hrm.staffing.domain.Employee;
import com.dayatang.utils.DateUtils;

@Entity
@Table(name = "pay_sp")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "sp_category", discriminatorType = DiscriminatorType.INTEGER)
public abstract class SalaryParameter extends AbstractEntity {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5224642013999225354L;

	private static SalaryParameterRepository salaryParameterRepository;

	protected static MessageSourceAccessor messages = CompensationMessageSource
			.getAccessor();

	// 废除日期
	@Column(name = "abolish_date")
	@Temporal(TemporalType.TIMESTAMP)
	private Date abolishDate = DateUtils.MAX_DATE;

	/*
	 * =======================================
	 * 
	 * transient
	 * 
	 * ========================================
	 */
	/**
	 * latestSetting为薪资参数具体设置的一个代理
	 */
	@Transient
	private SalaryParameterSetting latestSetting;
	@Transient
	private Value value;

	public SalaryParameter() {
	}

	public static SalaryParameterRepository getSalaryParameterRepository() {
		if (salaryParameterRepository == null) {
			salaryParameterRepository = InstanceFactory
					.getInstance(SalaryParameterRepository.class);
		}
		return salaryParameterRepository;
	}

	public static void setSalaryParameterRepository(
			SalaryParameterRepository salaryParameterRepository) {
		SalaryParameter.salaryParameterRepository = salaryParameterRepository;
	}

	public static MessageSourceAccessor getMessages() {
		return messages;
	}

	public static void setMessages(MessageSourceAccessor messages) {
		SalaryParameter.messages = messages;
	}

	public Date getAbolishDate() {
		return abolishDate;
	}

	public void setAbolishDate(Date abolishDate) {
		this.abolishDate = abolishDate;
	}

	SalaryParameterSetting getLatestSetting() {
		return latestSetting;
	}

	void setLatestSetting(SalaryParameterSetting latestSetting) {
		this.latestSetting = latestSetting;
	}

	public Value getValue() {
		return value;
	}

	public void setValue(Value value) {
		this.value = value;
	}

	// 代理属性
	public String getName() {
		return latestSetting.getName();
	}

	public void setName(String name) {
		latestSetting.setName(name);
	}

	public DataType getDataType() {
		return latestSetting.getDataType();
	}

	public void setDataType(DataType dataType) {
		latestSetting.setDataType(dataType);
	}

	public Integer getOrderSeq() {
		return latestSetting.getOrderSeq();
	}

	public void setOrderSeq(Integer orderSeq) {
		latestSetting.setOrderSeq(orderSeq);
	}

	public DataCalculatePolicy getDataCalculatePolicy() {
		return latestSetting.getDataCalculatePolicy();
	}

	public void setDataCalculatePolicy(DataCalculatePolicy dataCalculatePolicy) {
		latestSetting.setDataCalculatePolicy(dataCalculatePolicy);
	}

	public FiscalPeriodRangeSetting getFiscalPeriodRangeSetting() {
		return latestSetting.getFiscalPeriodRangeSetting();
	}

	public void setFiscalPeriodRangeSetting(
			FiscalPeriodRangeSetting fiscalPeriodRangeSetting) {
		latestSetting.setFiscalPeriodRangeSetting(fiscalPeriodRangeSetting);
	}

	public String getRemark() {
		return latestSetting.getRemark();
	}

	public void setRemark(String remark) {
		latestSetting.setRemark(remark);
	}

	public Date getCreated() {
		return latestSetting.getCreated();
	}

	public void setCreated(Date created) {
		latestSetting.setCreated(created);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof SalaryParameter == false) {
			return false;
		}
		if (this == obj) {
			return true;
		}
		SalaryParameter rhs = (SalaryParameter) obj;
		return new EqualsBuilder().append(getId(), rhs.getId()).isEquals();
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder(17, 37).append(getId()).toHashCode();
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this,
				ToStringStyle.SHORT_PREFIX_STYLE);
	}

	/*
	 * =======================================
	 * 
	 * action
	 * 
	 * ========================================
	 */

	private void save() {
		getSalaryParameterRepository().save(this);
	}

	/**
	 * 改正设置并保存（不会将设置备份）
	 */
	public void saveChanges() {
		save();
		latestSetting.saveChanges();
	}

	/**
	 * 备份原有设置并保存当前设置（会将之前的设置备份）
	 */
	public void archive() {
		save();
		latestSetting.archive();
	}

	public void remove() {
		getSalaryParameterRepository().remove(this);
	}

	public void abolish(Date abolishDate) {
		if (abolishDate == null) {
			abolishDate = new Date();
		}
		setAbolishDate(abolishDate);
		save();

		latestSetting.abolish(abolishDate);

	}

	protected abstract Value calculateValue(Employee employee, Date fromDate,
			Date toDate);

	public void assembleValue(Employee employee, Date fromDate, Date toDate) {
		setValue(calculateValue(employee, fromDate, toDate));
	}

	public static Set<SalaryParameter> findBySalaryAccountSuite(
			SalaryAccountSuite salaryAccountSuite, Date queryDate) {
		Set<SalaryParameter> allSalaryParameters = new HashSet<SalaryParameter>();

		// 薪资帐套下的薪资项目
		List<SalaryItem> salaryItems = salaryAccountSuite
				.getSalaryItems(queryDate);

		/*
		 * 
		 * 找出薪资帐套下，以及薪资公式计算时所需要的所有薪资计算项目
		 */
		Set<SalaryCalculateItem> allSalaryCalculateItems = new HashSet<SalaryCalculateItem>();
		// 加入直接属于薪资帐套下的薪资项目（薪水册下要包含的薪资项目）
		allSalaryCalculateItems.addAll(salaryItems);
		for (SalaryItem salaryItem : salaryItems) {
			List<CalculateRule> calculateRules = salaryItem
					.getCalculateRules(queryDate);
			for (CalculateRule rule : calculateRules) {
				// 加入薪资公式所依赖的薪资项目
				allSalaryCalculateItems.addAll(rule
						.getDependentSalaryCalculateItems(queryDate));
			}

		}

		// 找出所有薪资计算项目，在计算时需要的所有薪资参数
		for (SalaryCalculateItem salaryCalculateItem : allSalaryCalculateItems) {
			List<CalculateRule> calculateRules = salaryCalculateItem
					.getCalculateRules(queryDate);
			for (CalculateRule rule : calculateRules) {
				// 加入薪资公式所依赖的薪资参数
				allSalaryParameters.addAll(rule
						.getDependentSalaryParameters(queryDate));
			}

		}

		return allSalaryParameters;
	}

}
